package com.huarui.user.action;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.ewaf.framework.action.BaseAction;
import org.ewaf.framework.cookie.CookieManager;
import org.ewaf.framework.struts2.util.DateFormatUtil;
import org.ewaf.framework.util.DateUtil;
import org.ewaf.framework.util.HttpUtil;
import org.ewaf.framework.util.MD5Digester;
import com.huarui.user.error.UserError;
import com.huarui.user.model.CookieConstants;
import com.huarui.user.model.SessionMessage;
import com.huarui.user.model.User;
import com.huarui.user.security.UserHolder;
import com.huarui.user.service.UserService;
import com.opensymphony.xwork2.validator.annotations.FieldExpressionValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.StringLengthFieldValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;

/**
 * xzz
 * 
 * @author Administrator
 * 
 */
public class UserAction extends BaseAction {

	@SuppressWarnings("unused")
	private Logger logger = Logger.getLogger(UserAction.class);

	private static final long serialVersionUID = -2015280435167182372L;

	private String superPassword;

	private String password;

	private String password2;

	private String email;

	private SessionMessage sessionMessage;

	private String birthday;

	private String http_email;

	private String activeCode;
	
	private Map<String, Object> resultMap = new HashMap<String, Object>();

	
	public String getActiveCode() {
		return activeCode;
	}

	public void setActiveCode(String activeCode) {
		this.activeCode = activeCode;
	}
	public String getHttp_email() {
		return http_email;
	}

	public void setHttp_email(String http_email) {
		this.http_email = http_email;
	}
	public String getBirthday() {
		return birthday;
	}

	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}

	public SessionMessage getSessionMessage() {
		return sessionMessage;
	}

	public void setSessionMessage(SessionMessage sessionMessage) {
		this.sessionMessage = sessionMessage;
	}

	public String getSuperPassword() {
		return superPassword;
	}

	public void setSuperPassword(String superPassword) {
		this.superPassword = superPassword;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	private UserService userService;

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public Map<String, Object> getResultMap() {
		return resultMap;
	}

	private User user;

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	private List<User> userList;

	public List<User> getUserList() {
		return userList;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}

	public String getPassword2() {
		return password2;
	}

	public void setPassword2(String password2) {
		this.password2 = password2;
	}

	public String checkName() {
		String name = user.getName();
		if (StringUtils.isNotBlank(name)) {
			userList = userService.getByName(name);
		}

		return "checkNameResult";
	}

	/**
	 * 忘记密码
	 * 
	 * @return
	 */

	public String resetPasswordAccount() {

		CookieManager cookie = new CookieManager(httpServletRequest);

		cookie.removeCookie(httpServletResponse, null, CookieConstants.Cookie_PATH,
				CookieConstants.COOKIE_PERM);

		return SUCCESS;
	}

	public String sendPasswordEmail() {

		String email = user.getEmail();

		user = userService.getUserByEmail(email);		
		
		if (user == null) {

			throw new RuntimeException(UserError.USER_NOT_EXSIT.getChError());
		}

		user.setActiveCode(UUID.randomUUID().toString());
		
		user.setExpiredTime(new Date());

		try {

			userService.sendPasswordEmail(user);

		} catch (Exception e) {

			throw new RuntimeException("发送失败，请重新发送");
		}

		
		http_email="http://mail."+user.getEmail().substring(user.getEmail().indexOf("@")+1);
		
		 if(http_email.equals("http://mail.gmail.com")){
			 
			 http_email="http://mail.google.com";
			 
		 }

		return SUCCESS;

	}

	public String resetPasswordLoad() throws Exception {
		
		User user = userService.getUserByActiveCode(activeCode);
		
		if(user==null){
			
			throw new RuntimeException(UserError.EXPORED_TIME_WRONG.getChError());	
			
	  }
		
	    Date standardTime = DateUtil.addDays(user.getExpiredTime(), 1);

		Date nowTime = new Date();
		
	    Integer middle = nowTime.compareTo(standardTime);

		if(middle==1){
			
			throw new RuntimeException(UserError.EXPORED_TIME_WRONG.getChError());			
		}
			
		return SUCCESS;
	}

	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "password2", shortCircuit = true, key = "user.password2.required"),
			@RequiredStringValidator(fieldName = "password", shortCircuit = true, key = "user.password.required") }, stringLengthFields = {
			@StringLengthFieldValidator(fieldName = "password", minLength = "6", shortCircuit = true, key = "user.password.length.minerror"),
			@StringLengthFieldValidator(fieldName = "password2", minLength = "6", shortCircuit = true, key = "user.password.length.minerror") }, 
			fieldExpressions = { @FieldExpressionValidator(fieldName = "password2", expression = "password2==password", shortCircuit = true, key = "user.password2.same.error") })
	public String resetPasswordSubmit() {
		
		user = userService.getUserByActiveCode(activeCode);

		if (user == null) {

			throw new RuntimeException(UserError.USER_NOT_EXSIT.getChError());
		}

		user.setPassword(MD5Digester.digest(password));
		user.setActiveCode(null);
		user.setExpiredTime(null);
		try {

			userService.update(user);

		} catch (Exception e) {

			throw new RuntimeException(UserError.RESET_PASSWORD_FAILTURE.getChError());
		}

		return SUCCESS;

	}

	/**
	 * 修改密码
	 * 
	 * @return
	 */

	public String changePassword_submit() {

		HttpServletRequest request = HttpUtil.getRequest();

		String jsonAll = request.getParameter("jsonAll");

		JSONObject jsonObject = JSONObject.fromObject(jsonAll);

		sessionMessage = UserHolder.getCurrentSessionMessage();

		user = (User) userService.getById(sessionMessage.getUserId());

		if (user == null) {

			resultMap.put("failure", UserError.USER_NOT_EXSIT.getChError());

			return "json";

		}

		superPassword = jsonObject.getString("superPassword");
		password = jsonObject.getString("password");

		if (!MD5Digester.digest(superPassword).equals(user.getPassword())) {

			resultMap.put("failure", UserError.USER_NOT_EXSIT.getChError());

			return "json";
		}

		user.setPassword(MD5Digester.digest(password));
		try {

			userService.update(user);

		} catch (Exception e) {

			resultMap.put("failure", "修改密码失败");

			return "json";
		}

		resultMap.put("success", "OK");

		return "json";
	}

	public String rejectEmail() {
		userService.rejectEmail(user.getEmail());
		return "rejectEmail";
	}

	public String getByPyCode() {
		HttpServletRequest request = HttpUtil.getRequest();
		userList = userService.getByPyCode((String) request
				.getAttribute("pyCode"));

		return "userList";
	}

	public String index() {

		return "index";

	}

	public String query() throws IOException {

		sessionMessage = UserHolder.getCurrentSessionMessage();

		Integer userId = sessionMessage.getUserId();

		User user = null;

		try {
			user = (User) userService.getById(userId);

		} catch (Exception e) {

			resultMap.put("failure", "服务器正则升级中...");

			return "json";
		}

		JSONArray root = JSONArray.fromObject(user);

		resultMap.put("root", root);

		return "json";

	}

	public String modify() throws IOException {

		sessionMessage = UserHolder.getCurrentSessionMessage();

		@SuppressWarnings("unused")
		Integer companyId = sessionMessage.getCompanyId();

		HttpServletRequest request = HttpUtil.getRequest();

		String jsonAll = request.getParameter("jsonAll");

		JSONObject jsonObject = JSONObject.fromObject(jsonAll);

		user = getUser(jsonObject);
		
		try {

			userService.update(user);

		} catch (Exception e) {

			resultMap.put("failure", "修改失败");

			return "json";

		}

		resultMap.put("success", "OK");

		return "json";
	}

	private User getUser(JSONObject jsonObject) {

		User u = (User) userService.getById(jsonObject.getInt("id"));

		u.setBirthday(DateFormatUtil
				.parseDate(jsonObject.getString("birthday")));
		u.setEmail(jsonObject.getString("email"));
		u.setIdent(jsonObject.getString("ident"));
		u.setMemo(jsonObject.getString("memo"));
		u.setSex(jsonObject.getInt("sex"));
		u.setName(jsonObject.getString("name"));

		return u;

	}
	/**
	 * public String getUserMessage() {
	 * 
	 * sessionMessage = UserHolder.getCurrentSessionMessage();
	 * 
	 * user = userService.getUserByEmail(sessionMessage.getUserEmail());
	 * 
	 * birthday = DateFormatUtil.date(user.getBirthday());
	 * 
	 * return SUCCESS; }
	 * 
	 * public String modifyUserMsg() {
	 * 
	 * birthday = DateFormatUtil.date(user.getBirthday());
	 * 
	 * return SUCCESS; }
	 * 
	 * public String modifyUserMsg_submit() {
	 * 
	 * User u = userService.getUserByEmail(user.getEmail());
	 * 
	 * birthday = DateFormatUtil.date(user.getBirthday());
	 * 
	 * u.setBirthday(user.getBirthday());
	 * 
	 * u.setIdent(user.getIdent());
	 * 
	 * u.setName(user.getName());
	 * 
	 * u.setMemo(user.getMemo());
	 * 
	 * u.setSex(user.getSex());
	 * 
	 * userService.update(u);
	 * 
	 * return SUCCESS; }
	 */

}
